// fetch.js
const config = require('../config/index')
// 封装post和get请求
let header,
  cookie

function setCookie (res) {
  cookie = res
}

function request (option) {
  if (option.url[0] === '/') {
    option.url = `${config.domain}${option.url}`
    // 适配2个域名的接口
    header = 'application/x-www-form-urlencoded'
  } else {
    header = 'application/json'
  }
  if (option.contentType) {
    header = option.contentType
  }
  return new Promise((resolve, reject) => {
    wx.request({
      method: option.method,
      url: option.url,
      data: option.data || {},
      header: {
        'content-type': header,
        cookie
      },
      success (res) {
        console.log('请求地址')
        console.log(option.url)
        console.log('请求参数')
        console.log(option.data || {})
        console.log('返回结果')
        console.log(res)
        if (res.data.code === 0) {
          // code 状态码为拉新组内接口
          resolve(res.data.data)
        } else if (res.data.ret === '0' || res.data.ret === '200') {
          // ret 状态码为登录接口
          resolve(res)
        } else {
          res.data.message && wx.showToast({
            title: res.data.message,
            icon: 'none'
          })
          reject(res)
        }
      },
      fail: reject
    })
  })
}

function get (url, data, contentType) {
  return request({
    method: 'GET', url, data, contentType
  })
}

function post (url, data, contentType) {
  return request({
    method: 'POST', url, data, contentType
  })
}

// 暴露接口
module.exports = {
  get,
  post,
  setCookie
}
